package com.hnucm.cooklife.model;

import com.blankj.utilcode.util.NetworkUtils;
import com.hnucm.cooklife.base.BaseModel;
import com.hnucm.cooklife.bean.db.Foll;
import com.hnucm.cooklife.contract.foll.Contract;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;

public class FollModel extends BaseModel implements Contract.IFollModel {

//    public FollModel() {
//        setCookies(false);
//    }

    @Override
    public Observable<List<Foll>> loadFoll(int owner) {
        Observable<List<Foll>> loadFromLocal = Observable.create(emitter -> {
            List<Foll> follList = LitePal.findAll(Foll.class);
            emitter.onNext(follList);
            emitter.onComplete();
        });

        if(NetworkUtils.isConnected()){
            Observable<List<Foll>> loadFollFromNet = loadFollFromNet(owner);
            return loadFollFromNet;
        } else {
            return loadFromLocal;
        }
    }

    //加载并更新本地的Foll
    private Observable<List<Foll>> loadFollFromNet(int owner){
        return mApiServer.loadFoll(owner)
                .map(follData -> {
                    List<Foll> follList = new ArrayList<>();
                    follData.getData().stream().forEach(dataDTO -> {
                        Foll follDB = new Foll();
                        follDB.userId = dataDTO.getUserId();
                        follDB.userName = dataDTO.getUserName();
                        follDB.userContent = dataDTO.getUserContent();
                        follDB.niceDate = dataDTO.getNiceDate();
                        follDB.userHeader = dataDTO.getUserHeader();
//                        follDB.userPic = dataDTO.getUserPic();
                        follDB.userPic = (ArrayList<String>) dataDTO.getUserPic();
                        follList.add(follDB);
                    });

//                    if(follList.size() > 0){
//                        LitePal.deleteAll(Foll.class);
//                    }
//                    LitePal.saveAll(follList);
                    return follList;
                });
    }

    @Override
    public Observable<List<Foll>> refreshFoll(int owner) {
        return loadFollFromNet(owner);
    }
}
